package com.mdxl.shiro.controller;

import com.mdxl.shiro.service.UserService;
import com.mdxl.shiro.util.CommonUtil;
import com.mdxl.shiro.util.Result;
import com.mdxl.shiro.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author:MuJiuTian
 * @Description:登陆接口
 * @Date: Created in 下午11:00 2019/10/31
 */
@Controller
public class LoginController {

    @Autowired
    UserService userService;


    @GetMapping(value = {"/","/tologin"})
    public String index(){
        return "/login";
    }


    @GetMapping(value = "/every/{url}")
    public String every(@PathVariable("url") String url){
        return "/"+url;
    }

    /**
     * @Author：MuJiuTian
     * @Date：2019/11/4 上午9:53
     * @Description：简单的注册逻辑（只是针对shiro接下来的测试使用）
     */
    @GetMapping(value = "/regist")
    @ResponseBody
    public Result regist(String username, String password) {

        // 1、注册的账号、密码判断
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return Result.error("username or pwd is avaliable null");
        }

        // 2、随机生成salt[设置长度为6，false为包含数字和字母]
        String salt = CommonUtil.getRandStr(6,false);

        // 3、生成加密密码，存储在mysql中,这个加密后的密码会和shiro配置的加密方式一致，从而在身份认证时才可以成功
        String uid  = ShiroUtils.encryption(password,salt,2,true);

        // 4、注册用户，将数据存储到数据库
        userService.regist(username,salt,uid);

        return Result.success(uid);
    }


    @GetMapping(value = "/login")
    @ResponseBody
    public Result login(@RequestParam Map<String, Object> map) {
        String userName = map.get("username").toString();
        String password = map.get("password").toString();

        Subject subject = SecurityUtils.getSubject();

        // 认证前提前准备token
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        try{
            subject.login(token);
        } catch (Exception e){
            return Result.error("error");
        }
        return Result.success("success");
    }

    /**
     * @Author：MuJiuTian
     * @Date：2019/11/6 下午3:33
     * @Description：测试权限的接口
     */
    @RequiresPermissions("test_add")
    @GetMapping(value = "/auth")
    @ResponseBody
    public Result auth(String username){
        return Result.success(username);
    }
}
